/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hengtiansoft.lfy.chart.activity;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.NetworkResponse;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.hengtiansoft.lfy.chart.applib.controller.HXSDKHelper;
import com.google.gson.reflect.TypeToken;
import com.hengtiansoft.lfy.chart.DemoHXSDKHelper;
import com.hengtiansoft.lfy.LFYApplication;
import com.hengtiansoft.lfy.R;
import com.hengtiansoft.lfy.chart.action.UpdateGroupAvatarJson;
import com.hengtiansoft.lfy.base.BaseActivity;
import com.hengtiansoft.lfy.chart.bean.BaseResult;
import com.hengtiansoft.lfy.constants.Constants;
import com.hengtiansoft.lfy.chart.db.UserDao;
import com.hengtiansoft.lfy.utils.Config;
import com.hengtiansoft.lfy.widget.AlertDialog;
import com.hengtiansoft.lfy.widget.ExitGroupDialog;
import com.hengtiansoft.lfy.chart.net.JsonListRequest;
import com.hengtiansoft.lfy.chart.net.VolleyUtil;
import com.hengtiansoft.lfy.chart.utils.UserUtils;
import com.hengtiansoft.lfy.widget.ExpandGridView;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.EMLog;
import com.hyphenate.util.NetUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * 群组详情页面
 */
public class GroupDetailsActivity extends BaseActivity
        implements OnClickListener {
    private static final String TAG = "GroupDetailsActivity";
    private static final int REQUEST_CODE_ADD_USER = 0;
    private static final int REQUEST_CODE_EXIT = 1;
    private static final int REQUEST_CODE_EXIT_DELETE = 2;
    private static final int REQUEST_CODE_CLEAR_ALL_HISTORY = 3;
    private static final int REQUEST_CODE_ADD_TO_BALCKLIST = 4;
    private static final int REQUEST_CODE_EDIT_GROUPNAME = 5;

    String longClickUsername = null;

    private ExpandGridView userGridview;
    private String groupId;
    private ProgressBar loadingPB;
    // private Button exitBtn;
    // private Button deleteBtn;
    private EMGroup group;
    private GridAdapter adapter;
    private int referenceWidth;
    private int referenceHeight;
    private ProgressDialog progressDialog;
    private RelativeLayout mRlExit;
    private RelativeLayout mRlDelete;
    private RelativeLayout rl_switch_block_groupmsg;
    /**
     * 屏蔽群消息imageView
     */
    private ImageView iv_switch_block_groupmsg;
    /**
     * 关闭屏蔽群消息imageview
     */
    private ImageView iv_switch_unblock_groupmsg;
    private TextView tv_switch_block_groupmsg_line;
    public static GroupDetailsActivity instance;

    String st = "";
    // 清空所有聊天记录
    private RelativeLayout clearAllHistory;
    private RelativeLayout blacklistLayout;
    private RelativeLayout changeGroupNameLayout;
    private RelativeLayout idLayout;
    private TextView idText;
    private Context mContext;
    private UserDao userDao;
    private int GROUP = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        // 获取传过来的groupid
        groupId = getIntent().getStringExtra("groupId");
        group = EMClient.getInstance().groupManager().getGroup(groupId);

        // we are not supposed to show the group if we don't find the group
        if (group == null) {
            finish();
            return;
        }

        setContentView(R.layout.activity_group_details);
        instance = this;
        st = getResources().getString(R.string.people);
        clearAllHistory = (RelativeLayout) findViewById(R.id.clear_all_history);
        userGridview = (ExpandGridView) findViewById(R.id.gridview);
        loadingPB = (ProgressBar) findViewById(R.id.progressBar);
        mRlExit = (RelativeLayout) findViewById(R.id.rl_Exit_the_group_chat);
        mRlDelete = (RelativeLayout) findViewById(R.id.rl_dismiss_group);
        // exitBtn = (Button) findViewById(R.id.btn_exit_grp);
        // deleteBtn = (Button) findViewById(R.id.btn_exitdel_grp);
        blacklistLayout = (RelativeLayout) findViewById(R.id.rl_blacklist);
        changeGroupNameLayout = (RelativeLayout) findViewById(
                R.id.rl_change_group_name);
        idLayout = (RelativeLayout) findViewById(R.id.rl_group_id);
        idLayout.setVisibility(View.VISIBLE);
        idText = (TextView) findViewById(R.id.tv_group_id_value);
        tv_switch_block_groupmsg_line = (TextView) findViewById(
                R.id.tv_switch_block_groupmsg_line);
        rl_switch_block_groupmsg = (RelativeLayout) findViewById(
                R.id.rl_switch_block_groupmsg);

        iv_switch_block_groupmsg = (ImageView) findViewById(
                R.id.iv_switch_block_groupmsg);
        iv_switch_unblock_groupmsg = (ImageView) findViewById(
                R.id.iv_switch_unblock_groupmsg);

        rl_switch_block_groupmsg.setOnClickListener(this);

        Drawable referenceDrawable = getResources()
                .getDrawable(R.drawable.smiley_add_btn);
        referenceWidth = referenceDrawable.getIntrinsicWidth();
        referenceHeight = referenceDrawable.getIntrinsicHeight();
        userDao = new UserDao(this);
        idText.setText(groupId);
        if (group.getOwner() == null || "".equals(group.getOwner())
                || !group.getOwner()
                        .equals(EMClient.getInstance().getCurrentUser())) {
            mRlExit.setVisibility(View.GONE);
            mRlDelete.setVisibility(View.GONE);
            blacklistLayout.setVisibility(View.GONE);
            changeGroupNameLayout.setVisibility(View.GONE);
        }
        // 如果自己是群主，显示解散按钮
        if (EMClient.getInstance().getCurrentUser()
                .equals(group.getOwner())) {
            mRlExit.setVisibility(View.GONE);
            mRlDelete.setVisibility(View.VISIBLE);
            rl_switch_block_groupmsg.setVisibility(View.GONE);
            tv_switch_block_groupmsg_line.setVisibility(View.GONE);
        }

        ((TextView) findViewById(R.id.group_name)).setText(
                group.getGroupName() + "(" + group.getMemberCount() + st);
        List<String> members = new ArrayList<String>();
        members.addAll(group.getMembers());

        adapter = new GridAdapter(this, R.layout.grid, members);
        userGridview.setAdapter(adapter);

        // 保证每次进详情看到的都是最新的group
        updateGroup();

        // 设置OnTouchListener
        userGridview.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (adapter.isInDeleteMode) {
                        adapter.isInDeleteMode = false;
                        adapter.notifyDataSetChanged();
                        return true;
                    }
                    break;
                default:
                    break;
                }
                return false;
            }
        });

        clearAllHistory.setOnClickListener(this);
        blacklistLayout.setOnClickListener(this);
        changeGroupNameLayout.setOnClickListener(this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
            Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String st1 = getResources().getString(R.string.being_added);
        String st2 = getResources().getString(R.string.is_quit_the_group_chat);
        String st3 = getResources().getString(R.string.chatting_is_dissolution);
        String st4 = getResources().getString(R.string.are_empty_group_of_news);
        String st5 = getResources()
                .getString(R.string.is_modify_the_group_name);
        final String st6 = getResources()
                .getString(R.string.Modify_the_group_name_successful);
        final String st7 = getResources()
                .getString(R.string.change_the_group_name_failed_please);
        String st8 = getResources().getString(R.string.Are_moving_to_blacklist);
        final String st9 = getResources()
                .getString(R.string.failed_to_move_into);

        final String stsuccess = getResources()
                .getString(R.string.Move_into_blacklist_success);
        if (resultCode == RESULT_OK) {
            if (progressDialog == null) {
                progressDialog = new ProgressDialog(GroupDetailsActivity.this);
                progressDialog.setMessage(st1);
                progressDialog.setCanceledOnTouchOutside(false);
            }
            switch (requestCode) {
            case REQUEST_CODE_ADD_USER:// 添加群成员
                final String[] newmembers = data
                        .getStringArrayExtra("newmembers");
                progressDialog.setMessage(st1);
                progressDialog.show();
                addMembersToGroup(newmembers);
                GROUP = 1;
                UpdateGroupAvatarJson updateGroupAvatarJson1 = new UpdateGroupAvatarJson(
                        groupId);
                getGroupAvatarRequest(Constants.AddChatCroupsImg,
                        updateGroupAvatarJson1);

                break;
            case REQUEST_CODE_EXIT: // 退出群
                progressDialog.setMessage(st2);
                progressDialog.show();
                exitGrop();
                GROUP = 2;
                UpdateGroupAvatarJson updateGroupAvatarJson2 = new UpdateGroupAvatarJson(
                        groupId);
                getGroupAvatarRequest(Constants.AddChatCroupsImg,
                        updateGroupAvatarJson2);
                break;
            case REQUEST_CODE_EXIT_DELETE: // 解散群
                progressDialog.setMessage(st3);
                progressDialog.show();
                deleteGrop();
//                UpdateGroupAvatarJson updateGroupAvatarJson3 = new UpdateGroupAvatarJson(
//                        groupId);
//                getGroupAvatarRequest(Constant.AddChatCroupsImg,
//                        updateGroupAvatarJson3);
                break;
            case REQUEST_CODE_CLEAR_ALL_HISTORY:
                // 清空此群聊的聊天记录
                progressDialog.setMessage(st4);
                progressDialog.show();
                clearGroupHistory();
                break;

            case REQUEST_CODE_EDIT_GROUPNAME: // 修改群名称
                final String returnData = data.getStringExtra("data");
                if (!TextUtils.isEmpty(returnData)) {
                    progressDialog.setMessage(st5);
                    progressDialog.show();

                    new Thread(new Runnable() {
                        public void run() {
                            try {
                                EMClient.getInstance().groupManager()
                                        .changeGroupName(groupId, returnData);
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        ((TextView) findViewById(
                                                R.id.group_name)).setText(
                                                        returnData + "("
                                                                + group.getMemberCount()
                                                                + st);
                                        progressDialog.dismiss();
                                        Toast.makeText(getApplicationContext(),
                                                st6, 0).show();
                                    }
                                });

                            } catch (HyphenateException e) {
                                e.printStackTrace();
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        progressDialog.dismiss();
                                        Toast.makeText(getApplicationContext(),
                                                st7, 0).show();
                                    }
                                });
                            }
                        }
                    }).start();
                }
                break;
            case REQUEST_CODE_ADD_TO_BALCKLIST:
                progressDialog.setMessage(st8);
                progressDialog.show();
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            EMClient.getInstance().groupManager().blockUser(groupId,
                                    longClickUsername);
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    refreshMembers();
                                    progressDialog.dismiss();
                                    Toast.makeText(getApplicationContext(),
                                            stsuccess, 0).show();
                                }
                            });
                        } catch ( HyphenateException e) {
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    progressDialog.dismiss();
                                    Toast.makeText(getApplicationContext(), st9,
                                            0).show();
                                }
                            });
                        }
                    }
                }).start();

                break;
            default:
                break;
            }
        }
    }

    private void refreshMembers() {
        adapter.clear();

        List<String> members = new ArrayList<String>();
        members.addAll(group.getMembers());
        adapter.addAll(members);

        adapter.notifyDataSetChanged();
    }

    /**
     * 点击退出群组按钮
     * 
     * @param view
     */
    public void exitGroup(View view) {
        startActivityForResult(new Intent(this, ExitGroupDialog.class),
                REQUEST_CODE_EXIT);

    }

    /**
     * 点击解散群组按钮
     * 
     * @param view
     */
    public void exitDeleteGroup(View view) {
        startActivityForResult(
                new Intent(this, ExitGroupDialog.class).putExtra("deleteToast",
                        getString(R.string.dissolution_group_hint)),
                REQUEST_CODE_EXIT_DELETE);

    }

    /**
     * 清空群聊天记录
     */
    public void clearGroupHistory() {

        EMClient.getInstance().chatManager().deleteConversation(group.getGroupId(),true);
        progressDialog.dismiss();
        // adapter.refresh(EMChatManager.getInstance().getConversation(toChatUsername));

    }

    /**
     * 退出群组
     * 
     * @param
     */
    private void exitGrop() {
        String st1 = getResources()
                .getString(R.string.Exit_the_group_chat_failure);
        new Thread(new Runnable() {
            public void run() {
                try {
                    EMClient.getInstance().groupManager().leaveGroup(groupId);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            setResult(RESULT_OK);
                            finish();
                            if (ChatActivity.activityInstance != null)
                                ChatActivity.activityInstance.finish();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(),
                                    getResources().getString(
                                            R.string.Exit_the_group_chat_failure)
                                            + " " + e.getMessage(),
                                    1).show();
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 解散群组
     * 
     * @param
     */
    private void deleteGrop() {
        final String st5 = getResources()
                .getString(R.string.Dissolve_group_chat_tofail);
        new Thread(new Runnable() {
            public void run() {
                try {
                    EMClient.getInstance().groupManager().destroyGroup(groupId);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            setResult(RESULT_OK);
                            finish();
                            if (ChatActivity.activityInstance != null)
                                ChatActivity.activityInstance.finish();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(),
                                    st5 + e.getMessage(), 1).show();
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 增加群成员
     * 
     * @param newmembers
     */
    private void addMembersToGroup(final String[] newmembers) {
        final String st6 = getResources()
                .getString(R.string.Add_group_members_fail);
        new Thread(new Runnable() {

            public void run() {
                try {
                    // 创建者调用add方法
                    if (EMClient.getInstance().getCurrentUser()
                            .equals(group.getOwner())) {
                        EMClient.getInstance().groupManager().addUsersToGroup(groupId,
                                newmembers);
                    } else {
                        // 一般成员调用invite方法
                        EMClient.getInstance().groupManager().inviteUser(groupId,
                                newmembers, null);
                    }
                    Thread.sleep(500);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            refreshMembers();
                            ((TextView) findViewById(R.id.group_name))
                                    .setText(group.getGroupName() + "("
                                            + group.getMemberCount()
                                            + st);
                            progressDialog.dismiss();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(),
                                    st6 + e.getMessage(), 1).show();
                        }
                    });
                }
            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        String st6 = getResources().getString(R.string.Is_unblock);
        final String st7 = getResources().getString(R.string.remove_group_of);
        switch (v.getId()) {
        case R.id.rl_switch_block_groupmsg: // 屏蔽群组
            if (iv_switch_block_groupmsg.getVisibility() == View.VISIBLE) {
                EMLog.d(TAG, "change to unblock group msg");
                if (progressDialog == null) {
                    progressDialog = new ProgressDialog(
                            GroupDetailsActivity.this);
                    progressDialog.setCanceledOnTouchOutside(false);
                }
                progressDialog.setMessage(st6);
                progressDialog.show();
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            EMClient.getInstance().groupManager()
                                    .unblockGroupMessage(groupId);
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    iv_switch_block_groupmsg
                                            .setVisibility(View.INVISIBLE);
                                    iv_switch_unblock_groupmsg
                                            .setVisibility(View.VISIBLE);
                                    progressDialog.dismiss();
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    progressDialog.dismiss();
                                    Toast.makeText(getApplicationContext(), st7,
                                            1).show();
                                }
                            });

                        }
                    }
                }).start();

            } else {
                String st8 = getResources()
                        .getString(R.string.group_is_blocked);
                final String st9 = getResources()
                        .getString(R.string.group_of_shielding);
                EMLog.d(TAG, "change to block group msg");
                if (progressDialog == null) {
                    progressDialog = new ProgressDialog(
                            GroupDetailsActivity.this);
                    progressDialog.setCanceledOnTouchOutside(false);
                }
                progressDialog.setMessage(st8);
                progressDialog.show();
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            EMClient.getInstance().groupManager()
                                    .blockGroupMessage(groupId);
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    iv_switch_block_groupmsg
                                            .setVisibility(View.VISIBLE);
                                    iv_switch_unblock_groupmsg
                                            .setVisibility(View.INVISIBLE);
                                    progressDialog.dismiss();
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    progressDialog.dismiss();
                                    Toast.makeText(getApplicationContext(), st9,
                                            1).show();
                                }
                            });
                        }

                    }
                }).start();
            }
            break;

        case R.id.clear_all_history: // 清空聊天记录
            String st9 = getResources().getString(R.string.sure_to_empty_this);
            Intent intent = new Intent(GroupDetailsActivity.this,
                    AlertDialog.class);
            intent.putExtra("cancel", true);
            intent.putExtra("titleIsCancel", true);
            intent.putExtra("msg", st9);
            startActivityForResult(intent, REQUEST_CODE_CLEAR_ALL_HISTORY);
            break;

        case R.id.rl_blacklist: // 黑名单列表
            startActivity(new Intent(GroupDetailsActivity.this,
                    GroupBlacklistActivity.class).putExtra("groupId", groupId));
            break;

        case R.id.rl_change_group_name:
            startActivityForResult(new Intent(this, EditActivity.class)
                    .putExtra("data", group.getGroupName()),
                    REQUEST_CODE_EDIT_GROUPNAME);
            break;

        default:
            break;
        }

    }

    /**
     * 群组成员gridadapter
     * 
     * @author admin_new
     * 
     */
    private class GridAdapter extends ArrayAdapter<String> {

        private int res;
        public boolean isInDeleteMode;
        private List<String> objects;

        public GridAdapter(Context context, int textViewResourceId,
                           List<String> objects) {
            super(context, textViewResourceId, objects);
            this.objects = objects;
            res = textViewResourceId;
            isInDeleteMode = false;
        }

        @Override
        public View getView(final int position, View convertView,
                            final ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(getContext()).inflate(res,
                        null);
                holder.imageView = (ImageView) convertView
                        .findViewById(R.id.iv_avatar);
                holder.textView = (TextView) convertView
                        .findViewById(R.id.tv_name);
                holder.badgeDeleteView = (ImageView) convertView
                        .findViewById(R.id.badge_delete);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            final LinearLayout button = (LinearLayout) convertView
                    .findViewById(R.id.button_avatar);
            // 最后一个item，减人按钮
            if (position == getCount() - 1) {
                holder.textView.setText("");
                // 设置成删除按钮
                holder.imageView.setImageResource(R.drawable.smiley_minus_btn);
                // button.setCompoundDrawablesWithIntrinsicBounds(0,
                // R.drawable.smiley_minus_btn, 0, 0);
                // 如果不是创建者或者没有相应权限，不提供加减人按钮
                if (!group.getOwner()
                        .equals(EMClient.getInstance().getCurrentUser())) {
                    // if current user is not group admin, hide add/remove btn
                    convertView.setVisibility(View.INVISIBLE);
                } else { // 显示删除按钮
                    if (isInDeleteMode) {
                        // 正处于删除模式下，隐藏删除按钮
                        convertView.setVisibility(View.INVISIBLE);
                    } else {
                        // 正常模式
                        convertView.setVisibility(View.VISIBLE);
                        convertView.findViewById(R.id.badge_delete)
                                .setVisibility(View.INVISIBLE);
                    }
                    final String st10 = getResources()
                            .getString(R.string.The_delete_button_is_clicked);
                    button.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            EMLog.d(TAG, st10);
                            isInDeleteMode = true;
                            notifyDataSetChanged();
                        }
                    });
                }
            } else if (position == getCount() - 2) { // 添加群组成员按钮
                holder.textView.setText("");
                holder.imageView.setImageResource(R.drawable.smiley_add_btn);
                // button.setCompoundDrawablesWithIntrinsicBounds(0,
                // R.drawable.smiley_add_btn, 0, 0);
                // 如果不是创建者或者没有相应权限
                if (!group.isMemberAllowToInvite() && !group.getOwner()
                        .equals(EMClient.getInstance().getCurrentUser())) {
                    // if current user is not group admin, hide add/remove btn
                    convertView.setVisibility(View.INVISIBLE);
                } else {
                    // 正处于删除模式下,隐藏添加按钮
                    if (isInDeleteMode) {
                        convertView.setVisibility(View.INVISIBLE);
                    } else {
                        convertView.setVisibility(View.VISIBLE);
                        convertView.findViewById(R.id.badge_delete)
                                .setVisibility(View.INVISIBLE);
                    }
                    final String st11 = getResources()
                            .getString(R.string.Add_a_button_was_clicked);
                    button.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            EMLog.d(TAG, st11);
                            // 进入选人页面
                            startActivityForResult(
                                    (new Intent(GroupDetailsActivity.this,
                                            GroupPickContactsActivity.class)
                                                    .putExtra("groupId",
                                                            groupId)),
                                    REQUEST_CODE_ADD_USER);
                        }
                    });
                }
            } else { // 普通item，显示群组成员
                final String username = getItem(position);
                convertView.setVisibility(View.VISIBLE);
                button.setVisibility(View.VISIBLE);
                // Drawable avatar =
                // getResources().getDrawable(R.drawable.default_avatar);
                // avatar.setBounds(0, 0, referenceWidth, referenceHeight);
                // button.setCompoundDrawables(null, avatar, null, null);
                holder.textView.setText(username);
                if (Config.getUserName().toLowerCase()
                        .equals(username)) {
                    UserUtils.setCurrentUserAvatar(getContext(),
                            holder.imageView);
                } else {
                    UserUtils.setUserAvatar(getContext(), username,
                            holder.imageView);
                }
                // demo群组成员的头像都用默认头像，需由开发者自己去设置头像
                if (isInDeleteMode) {
                    // 如果是删除模式下，显示减人图标
                    convertView.findViewById(R.id.badge_delete)
                            .setVisibility(View.VISIBLE);
                } else {
                    convertView.findViewById(R.id.badge_delete)
                            .setVisibility(View.INVISIBLE);
                }
                final String st12 = getResources()
                        .getString(R.string.not_delete_myself);
                final String st13 = getResources()
                        .getString(R.string.Are_removed);
                final String st14 = getResources()
                        .getString(R.string.Delete_failed);
                final String st15 = getResources()
                        .getString(R.string.confirm_the_members);
                button.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isInDeleteMode) {
                            // 如果是删除自己，return
                            if (EMClient.getInstance().getCurrentUser()
                                    .equals(username)) {
                                startActivity(
                                        new Intent(GroupDetailsActivity.this,
                                                AlertDialog.class)
                                                        .putExtra("msg", st12));
                                return;
                            }
                            if (!NetUtils.hasNetwork(getApplicationContext())) {
                                Toast.makeText(getApplicationContext(),
                                        getString(R.string.network_unavailable),
                                        0).show();
                                return;
                            }
                            EMLog.d("group",
                                    "remove user from group:" + username);
                            deleteMembersFromGroup(username);
                        } else {
                            // 正常情况下点击user，可以进入用户详情或者聊天页面等等
                            if (Config.getUserName()
                                    .equals(username)) {
                                Toast.makeText(getContext(), getString(R.string.cannot_chart_myself),
                                        Toast.LENGTH_LONG).show();
                            } else {
                                if (((DemoHXSDKHelper) HXSDKHelper
                                        .getInstance()).getContactList()
                                                .containsKey(username)) {
                                    Intent intent = new Intent();
                                    intent.setClass(mContext,
                                            PersonalDetailsActivity.class);
                                    intent.putExtra("username", username);
                                    intent.putExtra("type", "send");
                                    mContext.startActivity(intent);
                                    // startActivity(new Intent(
                                    // GroupDetailsActivity.this,
                                    // ChatActivity.class).putExtra(
                                    // "userId", username));
                                } else {
                                    Intent intent = new Intent();
                                    intent.setClass(mContext,
                                            PersonalDetailsActivity.class);
                                    intent.putExtra("username", username);
                                    intent.putExtra("type", "add");
                                    mContext.startActivity(intent);
                                }

                            }
                        }
                    }

                    /**
                     * 删除群成员
                     * 
                     * @param username
                     */
                    protected void deleteMembersFromGroup(
                            final String username) {
                        final ProgressDialog deleteDialog = new ProgressDialog(
                                GroupDetailsActivity.this);
                        deleteDialog.setMessage(st13);
                        deleteDialog.setCanceledOnTouchOutside(false);
                        deleteDialog.show();
                        new Thread(new Runnable() {

                            @Override
                            public void run() {
                                try {
                                    // 删除被选中的成员
                                    EMClient.getInstance().groupManager()
                                            .removeUserFromGroup(groupId,
                                                    username);
                                    isInDeleteMode = false;
                                    runOnUiThread(new Runnable() {

                                        @Override
                                        public void run() {
                                            deleteDialog.dismiss();
                                            refreshMembers();
                                            ((TextView) findViewById(
                                                    R.id.group_name)).setText(
                                                            group.getGroupName()
                                                                    + "("
                                                                    + group.getMemberCount()
                                                                    + st);
                                        }
                                    });
                                    GROUP = 1;
                                    UpdateGroupAvatarJson updateGroupAvatarJson1 = new UpdateGroupAvatarJson(
                                            groupId);
                                    getGroupAvatarRequest(
                                            Constants.AddChatCroupsImg,
                                            updateGroupAvatarJson1);
                                } catch (final Exception e) {
                                    deleteDialog.dismiss();
                                    runOnUiThread(new Runnable() {
                                        public void run() {
                                            Toast.makeText(
                                                    getApplicationContext(),
                                                    st14 + e.getMessage(), 1)
                                                    .show();
                                        }
                                    });
                                }

                            }
                        }).start();
                    }
                });

                button.setOnLongClickListener(new OnLongClickListener() {

                    @Override
                    public boolean onLongClick(View v) {
                        if (EMClient.getInstance().getCurrentUser()
                                .equals(username))
                            return true;
                        if (group.getOwner().equals(
                                EMClient.getInstance().getCurrentUser())) {
                            Intent intent = new Intent(
                                    GroupDetailsActivity.this,
                                    AlertDialog.class);
                            intent.putExtra("msg", st15);
                            intent.putExtra("cancel", true);
                            startActivityForResult(intent,
                                    REQUEST_CODE_ADD_TO_BALCKLIST);
                            longClickUsername = username;
                        }
                        return false;
                    }
                });
            }
            return convertView;
        }

        @Override
        public int getCount() {
            return super.getCount() + 2;
        }
    }

    protected void updateGroup() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    final EMGroup returnGroup = EMClient.getInstance().groupManager()
                            .getGroupFromServer(groupId);
                    // 更新本地数据
                  //  EMGroupManager.getInstance()
                   //         .createOrUpdateLocalGroup(returnGroup);

                    runOnUiThread(new Runnable() {
                        public void run() {
                            ((TextView) findViewById(R.id.group_name))
                                    .setText(group.getGroupName() + "("
                                            + group.getMemberCount()
                                            + ")");
                            loadingPB.setVisibility(View.INVISIBLE);
                            refreshMembers();
                            if (EMClient.getInstance().getCurrentUser()
                                    .equals(group.getOwner())) {
                                // 显示解散按钮
                                mRlExit.setVisibility(View.GONE);
                                mRlDelete.setVisibility(View.VISIBLE);
                            } else {
                                // 显示退出按钮
                                mRlExit.setVisibility(View.VISIBLE);
                                mRlDelete.setVisibility(View.GONE);
                            }

                            // update block
                            EMLog.d(TAG, "group msg is blocked:"
                                    + group.isMsgBlocked());
                            if (group.isMsgBlocked()) {
                                iv_switch_block_groupmsg
                                        .setVisibility(View.VISIBLE);
                                iv_switch_unblock_groupmsg
                                        .setVisibility(View.INVISIBLE);
                            } else {
                                iv_switch_block_groupmsg
                                        .setVisibility(View.INVISIBLE);
                                iv_switch_unblock_groupmsg
                                        .setVisibility(View.VISIBLE);
                            }
                        }
                    });

                } catch (Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            loadingPB.setVisibility(View.INVISIBLE);
                        }
                    });
                }
            }
        }).start();
    }

    public void back(View view) {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_OK);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        instance = null;
    }

    private static class ViewHolder {
        ImageView imageView;
        TextView textView;
        ImageView badgeDeleteView;
    }

    /**
     * 获取群组头像
     * 
     * @param getGroupAvatarUrl
     * @param
     */
    private void getGroupAvatarRequest(String getGroupAvatarUrl,
            UpdateGroupAvatarJson mUpdateGroupAvatarJson) {
        Log.i(TAG,
                "<getGroupAvatarRequest>--<onResponse>--上传的JSon数据：  GetTokenJson = "
                        + mUpdateGroupAvatarJson);
        java.lang.reflect.Type type = new TypeToken<BaseResult>() {
        }.getType();
        JsonListRequest<BaseResult> request = new JsonListRequest<BaseResult>(
                mContext, Method.POST, getGroupAvatarUrl,
                mUpdateGroupAvatarJson.toString(), null, null, type, false,
                new Listener<BaseResult>() {

                    @Override
                    public void onResponse(BaseResult arg0) {
                        Log.i(TAG,
                                "<getGroupAvatarRequest>--<onResponse>--服务器返回的JSon数据：  arg0 = "
                                        + arg0);
                        int code = 1;
                        String message = null;
                        String data = null;
                        message = arg0.getMessage();
                        code = arg0.getCode();
                        data = (String) arg0.getData();
                        Log.i(TAG,
                                "<getGroupAvatarRequest>--<onResponse>--服务器返回的JSon数据：  message = "
                                        + message);
                        Log.i(TAG,
                                "<getGroupAvatarRequest>--<onResponse>--服务器返回的JSon数据：  code = "
                                        + code);
                        Log.i(TAG,
                                "<getGroupAvatarRequest>--<onResponse>--服务器返回的JSon数据：  data = "
                                        + data);
                        if (code == 0) {
                            if (data != null) {
                                // 保存至数据库
                                if (GROUP == 1) {
                                    ContentValues values = new ContentValues();
                                    values.put(UserDao.GROUP_AVATAR_ID,
                                            groupId);
                                    values.put(UserDao.GROUP_AVATAR_NAME,
                                            group.getGroupName());
                                    values.put(UserDao.GROUP_AVATAR, data);
                                    userDao.updateGroupAvatar(groupId, values);
                                } else if (GROUP == 2) {
                                    userDao.deleteGroupAvatar(groupId);
                                }
                            }
                        } else {
                            Toast.makeText(mContext, message, Toast.LENGTH_LONG)
                                    .show();
                        }
                    }
                }, new ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError arg0) {
                        NetworkResponse response = arg0.networkResponse;
                        if (response != null) {
                            try {
                                String json = new String(response.data,
                                        HttpHeaderParser.parseCharset(
                                                response.headers));
                                Log.i(TAG,
                                        "<getTokenRequest>--<onErrorResponse> -- json = "
                                                + json);
                                Log.i(TAG,
                                        "<getTokenRequest>--<onErrorResponse> -- response.data = "
                                                + response.data);
                                Log.i(TAG,
                                        "<getTokenRequest>--<onErrorResponse> -- response.headers = "
                                                + response.headers);
                                // showToast(mContext, json,
                                // Toast.LENGTH_SHORT);
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                        if (arg0 != null && arg0.toString().contains(
                                "com.android.volley.NoConnectionError")) {
                            Toast.makeText(mContext,
                                    getString(R.string.network_unavailable),
                                    Toast.LENGTH_SHORT).show();
                        } else if (arg0 != null && arg0.toString()
                                .contains("com.android.volley.ServerError")) {
//                            Toast.makeText(mContext,
//                                    getString(
//                                            R.string.service_temporarily_unavailable),
//                                    Toast.LENGTH_SHORT).show();
                        } else if (arg0 != null && arg0.toString()
                                .contains("com.android.volley.TimeoutError")) {
                            Toast.makeText(mContext,
                                    getString(R.string.time_out_error),
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(mContext,
                                    getString(R.string.request_fail),
                                    Toast.LENGTH_SHORT).show();
                        }
                        Log.i(TAG,
                                "<getTokenRequest>--<onErrorResponse>--服务器请求失败： arg0 = "
                                        + arg0);
                        Log.i(TAG,
                                "<getTokenRequest>--<onErrorResponse>--服务器请求失败： response = "
                                        + response);
                    }

                });
        VolleyUtil.addRequest(request);
    }
}
